package cn.wolfcode.demo.controller;

import cn.wolfcode.demo.domain.User;
import cn.wolfcode.demo.service.IUserService;
import cn.wolfcode.demo.Json.JsonResult;
import cn.wolfcode.demo.service.MongoUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MongoUserService mongoUserService;
    @Autowired
    private JavaMailSender mailSender;

    @GetMapping("/list")
    public Object list() {
        List<User> list = userService.list();
        return list;
    }


    @GetMapping("/get")
    public Object get(User user) {
        User user1 = userService.getUserByName(user.getUsername());
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom("2546022374@qq.com");
        mailMessage.setSubject("作业");
        if (user1 != null){
            if (user1.getPassword().equals(user.getPassword())) {
            mailMessage.setText("用户名："+user1.getUsername()+"密码："+user1.getPassword());
            mailMessage.setTo("2546022374@qq.com");
            mailSender.send(mailMessage);
            return new JsonResult();
        } else {
            return new JsonResult(false, "密码错误");
        }
    }else {
        return new JsonResult(false, "用户名不存在");
    }

    }


    @GetMapping("/save")
    public Object save(User user) {
        User user1 = userService.getUserByName(user.getUsername());
        if (user1 != null) {
           return new JsonResult(false,"用户名已存在，请重新注册");
        } else {
            boolean sava = userService.save(user);
            if (sava){
                ValueOperations valueOperations = redisTemplate.opsForValue();
                valueOperations.set("user"+ user.getUsername(),user);
                userService.save(user);
                return new JsonResult();
            }else {
                return new JsonResult(false,"注册失败");
            }
        }
    }
}
